﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Common
{
    public static class CookieHelper
    {
        // Methods
        public static string GetValue(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
            if (cookie != null)
            {
                return cookie.Value.UrlDecode();
            }
            return null;
        }

        public static string GetValue(string key, Func<string> getValueFunc)
        {
            string str = GetValue(key);
            if (str == null)
            {
                str = getValueFunc();
                if (HttpContext.Current.Request.Cookies[key] == null)
                {
                    SetValue(key, str);
                    return str;
                }
            }
            return str;
        }

        public static void Remove(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
            if (cookie!=null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            //HttpContext.Current.Request.Cookies.Remove(key);
        }

        public static void SetValue(string key, Func<string> getValueFunc)
        {
            SetValue(key, getValueFunc());
        }

        public static void SetValue(string key, object value)
        {
            if (value == null)
            {
                HttpContext.Current.Response.Cookies.Remove(key);
            }
            else
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
                if (cookie != null)
                {
                    cookie.Value = value.ToString();
                    HttpContext.Current.Response.AppendCookie(cookie);
                }
                else
                {
                    HttpContext.Current.Response.AppendCookie(new HttpCookie(key, value.ToString().UrlEncode()));
                }
            }
        }
    }

 

}
